class ProcessActiveInstance < ActiveRecord::Base
  include RBPM::Toolkit
  include RBPM::Execute
  include RBPM::Params

  # 获取当前活动实例在BPMN图上的节点
  def node
    @node ||= get_node
  end

  # 提交当前活动实例完成
  def finish!(parameters={})
    # 初始化流程变量
    process_variables_init self.process_instance
    @parameters = @parameters.merge parameters

    # 获取下一个流，得到targetRef
    the_next_flow = node.next
    eval(node.beforeEnd) if defined? node.beforeEnd
    yield if block_given?
    # 可能后面不存在流程，
    target_ref = the_next_flow.nil? ? 'stoped' : the_next_flow.targetRef
    self.update_attributes status: 0, end_date: Time.now, executor: parameters[:active_executor_id], bpmn_next_target_ref: target_ref
    eval(node.afterEnd) if defined? node.afterEnd

    auto_run the_next_flow, @parameters
  end

  # 状态标题
  def status_title
    case self.status
      when 0
        '完成'
      when 1
        '启动'
      when 2
        '暂停'
      when 3
        '异常'
      else
        '未知'
    end
  end

  # 活动类型标题
  def active_type_title
    case self.active_type
      when 0
        '服务任务'
      when 1
        '用户任务'
      when 2
        '并行网关'
      when 3
        '排他网关'
      else
        '未知'
    end
  end

  private

  def get_node
    # 判断当前流程实例是否存在，  从实例中读取流程定义的文件信息
    if self.process_instance_id
      version = self.version || nil
      doc = RBPM::Parser.read(self.process_instance.process_define.bpmn_file(version))
      node = doc.at_css("##{self.bpmn_active_define_id}")

      @node = active_instance_class.new(node, doc, self.process_instance)
    end
  end

end
